package com.sikaryofficial.backend.message.consumer;

import cn.hutool.core.text.CharSequenceUtil;
import com.sikaryofficial.backend.message.body.ScanRegisterMessage;
import com.sikaryofficial.backend.service.IPointsDetailStrategy;
import com.sikaryofficial.common.core.constant.PointRuleConstant;
import com.sikaryofficial.common.core.context.SecurityContextHolder;
import com.sikaryofficial.common.core.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

@Component
@Slf4j
public class ScanRegisterProcess {

    @Resource
    private Map<String, IPointsDetailStrategy> pointsDetailStrategyMap;

    /**
     * 消息监听
     * <p>
     * 扫码注册-消费流程
     *
     * @param message 消息
     */
    @StreamListener(MQConsumer.BINDINGS_SCAN_REGISTER_INPUT)
    public void onScanRegisterMessage(@Payload ScanRegisterMessage message) {
        log.info("=============onScanRegisterMessage============######start##########==================================");
        log.info("[onMessage][线程编号:{} 消息内容：{}]", Thread.currentThread().getId(), message);
        log.info("==============onScanRegisterMessage============###################===============================");
        Long userId = message.getUserId();
        // 设置品牌
        if(CharSequenceUtil.isNotBlank(message.getBrand())){
            SecurityContextHolder.setBrand(message.getBrand());
        }
        // 积分获取
        IPointsDetailStrategy pointsDetailStrategy = pointsDetailStrategyMap.get(PointRuleConstant.SCAN_REGISTER + IPointsDetailStrategy.SUFFIX);
        if (Objects.isNull(userId) || Objects.equals(userId, 0L)) {
            throw new ServiceException("user not login.");
        }
        // 2、扫描注册得20积分
        pointsDetailStrategy.updatePointsByInputValue(userId, userId, message.getPoints(),null,"");
        // 清除品牌
        SecurityContextHolder.remove();
        log.info("=============onScanRegisterMessage=============########end###########========");
    }
}
